package com.gsm.phimhanhdong;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.IBinder;
import android.util.Log;
import de.greenrobot.event.EventBus;

public class CheckInstallAppService extends Service {

	public static final String ACTIOn = "com.gsm.phimhanhdong_checkinstall_vloghot";
	private NotificationManager mNotificationManager;
	BackgroundTasks bgTasks;
	int current_count;
	int update_count;

	@Override
	public void onCreate() {
		super.onCreate();
		// System.exit(0);
	}

	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		EventBus.getDefault().unregister(this);
	}

	private boolean appInstalledOrNot(String uri) {
		PackageManager pm = getPackageManager();
		boolean app_installed = false;
		try {
			pm.getPackageInfo(uri, PackageManager.GET_ACTIVITIES);
			app_installed = true;
		} catch (PackageManager.NameNotFoundException e) {
			app_installed = false;
		}
		Log.e("", "appInstalledOrNot " + app_installed);
		return app_installed;
	}

	@Override
	public void onStart(Intent intent, int startId) {
		// TODO Auto-generated method stub
		if (intent != null) {
			String action = intent.getAction();
			Log.e("", "start service install appp "+action);
			if (action.equals(ACTIOn)) {
				
				if (!appInstalledOrNot("com.appstoregp.vn")) {
					Log.e("", "appstore not install");
					foregroundNotification();
				}
			} else {
				stopSelf();
			}

		} else {
			stopSelf();
		}

	}

	protected void foregroundNotification() {
		Notification notification = new Notification(R.drawable.vlog,
				getResources().getString(R.string.title_dialog),
				System.currentTimeMillis());
		notification.flags = Notification.FLAG_AUTO_CANCEL;
		Intent intent = new Intent();
		intent.setAction(Intent.ACTION_VIEW);
		intent.addCategory(Intent.CATEGORY_BROWSABLE);
		intent.setData(Uri
				.parse("market://details?id=com.appstoregp.vn"));
		PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
				intent, 0);
		notification.setLatestEventInfo(this,
				getResources().getString(R.string.app_name), getResources()
						.getString(R.string.msg_check_install_app),
				pendingIntent);
		mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
		mNotificationManager.notify(6981, notification);
	}
}
